from pptflow.utils import mylogger
import os

logger = mylogger.get_logger(__name__)

def get_tts_service(tts_service_provider: str):
    # import tts module according to service provider
    if not tts_service_provider:
        logger.error("tts service provider is null")
        raise NotImplementedError(f"tts service provider can't be null")
    
    # Normalize the provider name to lowercase for case-insensitive comparison
    provider = tts_service_provider.lower()
    logger.info(f"Initializing TTS service provider: {provider}")
    
    try:
        if provider == "azure":
            from .tts_azure import AzureTtsService
            return AzureTtsService()
        elif provider == "kokoro":
            from .tts_kokoro import KokoroTtsService
            return KokoroTtsService()
        elif provider == "baidu":
            from .tts_baidu import BaiduTtsService
            return BaiduTtsService()
        elif provider == "fish_speech" or provider == "fish-speech" or provider == "fishspeech":
            from .tts_fish_speech import FishSpeechTtsService
            return FishSpeechTtsService()
        elif provider == "cosyvoice" or provider == "cosy-voice" or provider == "cosy_voice" or provider == "cosyvoice_v1":
            from .tts_cosyvoice import CosyVoiceTtsService
            return CosyVoiceTtsService()
        elif provider == "cosyvoice_v2" or provider == "cosy-voice-v2" or provider == "cosy_voice_v2":
            from .tts_cosyvoice_v2 import CosyVoiceV2TtsService
            return CosyVoiceV2TtsService()
        else:
            # Try to use CosyVoice V2 as fallback if available
            try:
                from .tts_cosyvoice_v2 import CosyVoiceV2TtsService
                logger.warning(f"Unknown TTS provider '{tts_service_provider}'. Falling back to CosyVoice V2.")
                return CosyVoiceV2TtsService()
            except ImportError:
                pass
                
            logger.error(f"Unsupported TTS service provider: {tts_service_provider}")
            raise NotImplementedError(f"Unsupported TTS service provider: {tts_service_provider}")
    except Exception as e:
        logger.error(f"Error initializing TTS service '{tts_service_provider}': {str(e)}")
        raise
